using Microsoft.AspNetCore.Mvc;
using TodoApi.Dto;
using TodoApi.Domain;
using TodoApi.IRepository;

namespace TodoApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class BlogsController : ControllerBase
{
    //定义一个私有的字段
    private readonly IRepository<Blogs> _db;
    //通过依赖注入，可以自动获取容器中对应类型（服务）的实例，把获得的实例赋值给私有的字段
    public BlogsController(IRepository<Blogs> db)
    {
        _db = db;
    }
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var list =await _db.GetAllAsync();
        return Ok(new {Code=1000,Msg="获取列表成功",Data=list});
    }

    [HttpPost]
    public async Task<IActionResult> Post(BlogCreateDto blogCreateDto)
    {
        var blog = new Blogs { Title = blogCreateDto.Title, Author = blogCreateDto.Author, Content = blogCreateDto.Content };
        var obj =await  _db.CreateAsync(blog);
        return Ok( new { Code = 1000, Data = obj, Msg = "新增成功" });
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Put(int id, BlogCreateDto blogCreateDto)
    {
        var blog =await _db.GetByIdAsync(id);
        if (blog == null)
        {
            return Ok(new { Code = 1004, Data = "", Msg = "你要修改的内容不存在" });
        }


        blog.Title = blogCreateDto.Title;
        blog.Author = blogCreateDto.Author;
        blog.Content = blogCreateDto.Content;

        await _db.UpdateAsync(blog);
        return Ok(new { Code = 1000, Data = blog, Msg = "修改成功" });
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        var blog =await _db.GetByIdAsync(id);
        if (blog == null)
        {
            return Ok(new { Code = 1004, Data = "", Msg = "你要删除的内容不存在" });
        }
        await _db.DeleteAsync(blog);
        return Ok(new { Code = 1004, Data = "", Msg = "删除成功" });
    }
}